package nuc.edu.cn.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
public class RedisWorkerId {
    public static final long BEGIN_TIMESTAMP = 1640995200;
    public static final long COUNT_BIT = 32;
    @Autowired
    StringRedisTemplate redisTemplate;
    public long nextId(String keyPrefix){
        //1.生成时间戳
        long NOW_TIMESTAMP = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC);
        long nowStamp = NOW_TIMESTAMP - BEGIN_TIMESTAMP;
        //2.生成序列号
        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yy-MM-dd"));
        Long count = redisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + time);
        return nowStamp<< COUNT_BIT | count;
    }

//    public static void main(String[] args) {
//        LocalDateTime localDateTime = LocalDateTime.of(2022, 1, 1, 0, 0, 0);
//        long epochSecond = localDateTime.toEpochSecond(ZoneOffset.UTC);
//        System.out.println(epochSecond);
//    }
}
